<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 李邦琦 <1536549251@qq.com>
// +----------------------------------------------------------------------

namespace app\crm\model;
use think\Db;
use think\Model;
use think\Cache;
use think\Loader;

class Callplatform extends Model
{
    /**
     * 获取当前坐席任务列表
     * @return array <日任务列表信息>
     */
    public function taskList()
    {
        $username = $_SESSION['user_info']['username'];
        $page = $_REQUEST["page"];
        $limit = $_REQUEST["limit"];
        $count = Db::table('bgcrm.sales_task')->field('id,name')->where("agent_task LIKE '%$username%'")->count();
        // 查询状态为1的用户数据 并且每页显示10条数据
        $taskList = Db::table('bgcrm.sales_task')->field('id,name')->where("agent_task LIKE '%$username%'")->limit(($page-1)*$limit,$limit)->order('createtime DESC')->select();
        // echo $taskList;exit;
        // print_r($taskList);exit;
        $rowsList = count($taskList) ? $taskList : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;
        return $arrData;
    }


    /**
     * 转交号码到号码池
     * @param  string $id       任务id
     * @param  string $tables   号码池表名
     * @return JSON             转交结果
     */
    public function transferCustomer ($id, $tables)
    {
        $customerList = Db::table("bgcrm.sales_source_$id")->field('customer_code, name, phone1, import_mark, address')->limit($_REQUEST['limit'])->select();
        foreach ($customerList as $key => $val) {
            if (empty($val['customer_code'])) {
                $val['customer_code'] = $this->createCustomerCode();
            }
            $data = array(
                'customer_code' => $val['customer_code'],
                'name' => $val['name'],
                'import_mark' => $_REQUEST['import_mark'],
                'phone' => $val['phone1'],
                'import_address' => $val['address'],
                'createtime' =>date('Y-m-d H:i:s'),
            );
            Db::table("bgcrm.sales_source_$id")->where('phone1="'.$val['phone1'].'"')->delete();
            $result[] = Db::name($tables)->insert($data);
        }
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'操作成功！'));
        } else {
            echo json_encode(array('msg'=>'操作失败！'));
        }
    }


    /**
     * 获取当前被呼叫的客户资料
     * @param  string $phone 客户电话
     * @param  string $id    任务id
     * @return array         客户资料数组
     */
    public function getCustomerData ($phone, $id)
    {
        $menuname = "Call Platform";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname]; 
        $username = $_SESSION["user_info"]["username"];

        $customerData = Db::table("bgcrm.sales_source_$id")->field('customer_code, createuser, name, age, sex,province,city,district, phone1, import_mark, address')->where('phone1='.$phone)->find();
        if (empty($customerData['customer_code'])) {
            $customer_code = $this->createCustomerCode();
            $data = array(
                'createuser' => $_SESSION['user_info']['username'],
                'customer_code' => $customer_code,
            );
            Db::table("bgcrm.sales_source_$id")->where('phone1='.$phone)->update($data);
        } else {
            // 弹屏后更新归属人
            $data = array(
                'createuser' => $_SESSION['user_info']['username'],
            );
            Db::table("bgcrm.sales_source_$id")->where('phone1='.$phone)->update($data);
        }

        if($priv["encrypt_phone"] == "Y"){
            if($username != "admin"){
                $customerData["phone1"] = substr($customerData["phone1"],0,3)."*****".substr($customerData["phone1"],-2);
            }
        }
        return $customerData;
    }


    /**
     * 获取当前被呼叫的客户资料
     * @param  string $customer_code 客户电话
     * @param  string $id    任务id
     * @return array         客户资料数组
     */
    public function getMyCustomerData ($customer_code, $id)
    {
        $menuname = "Call Platform";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname]; 
        $username = $_SESSION["user_info"]["username"];
        
        $customerData = Db::table("bgcrm.sales_source_$id")->field('customer_code, createuser, name, age, sex,province,city,district, phone1, import_mark, address')->where('customer_code="'.$customer_code.'"')->find();
        if (empty($customerData['customer_code'])) {
            $customer_code = $this->createCustomerCode();
            $data = array(
                'createuser' => $_SESSION['user_info']['username'],
                'customer_code' => $customer_code,
            );
            Db::table("bgcrm.sales_source_$id")->where('customer_code="'.$customer_code.'"')->update($data);
        }

        if($priv["encrypt_phone"] == "Y"){
            if($username != "admin"){
                $customerData["phone1"] = substr($customerData["phone1"],0,3)."*****".substr($customerData["phone1"],-2);
            }
        }
        return $customerData;
    }


    /**
     * 外呼会员资料列表
     * @return [type] [description]
     */
    public function saleSourceData($where)
    {
        header("Content-Type:text/html; charset=utf-8");
        
        $menuname = "Call Platform";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname]; 
        $username = $_SESSION["user_info"]["username"];


        $page = $_REQUEST["page"];
        $limit = $_REQUEST["limit"];
        $id = $_REQUEST["id"];
        $count = Db::table("bgcrm.sales_source_$id")->where($where)->count();
        $dataList = Db::table("bgcrm.sales_source_$id")->where($where)->limit(($page-1)*$limit,$limit)->order("createtime desc")->select();
        $users = Cache::get('users');
        $calledflag = array("1"=>"未呼叫","2"=>"未接听","3"=>"已接听");
        $i = 0;
        foreach($dataList as &$val){
            $val['address'] = $val['province'].$val['city'].$val['district'];
            $val["createuser"] = $users[$val["createuser"]]["cn_name"];
            $val["calledflag"] = $calledflag[$val["calledflag"]];
            $i++;
            
            if($priv["encrypt_phone"] == "Y"){
                if($username != "admin"){
                    $val["phone1"] = substr($val["phone1"],0,3)."*****".substr($val["phone1"],-2);
                    $val["phone2"] = substr($val["phone2"],0,3)."*****".substr($val["phone2"],-2);
                }
            }
        }
        unset($i);
        $rowsList = count($dataList) ? $dataList : false;
        $arrCate["code"] = 0;
        $arrCate["msg"] = '';
        $arrCate["count"] = $count;
        $arrCate["data"] = $rowsList;
        
        return $arrCate;
    }


    /**
     * 从外呼往三张表插入客户资料
     * @param  string $id            外呼任务id
     * @param  string $customer_code 客户资料编码
     * @return bool                  是否成功
     */
    public function insertCustomer ($id, $customer_code)
    {
        $customerData = Db::table("bgcrm.sales_source_$id")->field('customer_code, createuser, name, age, sex, province, city, district, phone1, import_mark, address')->where('customer_code="'.$customer_code.'"')->find();
        $dataBasic = array(
            'customer_code' => $customerData['customer_code'],
            'create_user' => $_SESSION['user_info']['username'],
            'name' => $customerData['name'],
            'phone' => $customerData['phone1'],
            'import_mark' => $customerData['import_mark'],
            'createtime' => date('Y-m-d H:i:s'),
        );
        $return_basic = Db::name('vip_customer_basic')->insert($dataBasic);

        $dataDetail = array(
            'customer_code' => $customerData['customer_code'],
            'age' => $customerData['age'],
            'sex' => $customerData['sex'],
            'last_call_time' => date('Y-m-d H:i:s'),
        );
        $return_detail = Db::name('vip_customer_detail')->insert($dataDetail);

        $dataAddress = array(
            'customer_code' => $customerData['customer_code'],
            'province' => $customerData['province'],
            'city' => $customerData['city'],
            'area' => $customerData['district'],
            'address_details' => $customerData['address'],
        );
        $return_address = Db::name('vip_customer_address')->insert($dataAddress);
        if ($return_basic && $return_detail && $return_address) {
            $customerData = Db::table("bgcrm.sales_source_$id")->where('customer_code="'.$customer_code.'"')->delete();
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取外呼中的客户资料
     * @param  string $customer_code    客户编码
     * @param  string $id               任务id
     * @return array                    客户资料数组
     */
    public function getAddOrder ($customer_code, $id)
    {
        $customerData = Db::table("bgcrm.sales_source_$id")->field('customer_code, createuser, name, age, sex,province,city,district, phone1, import_mark, address')->where('customer_code="'.$customer_code.'"')->find();
        $customerData['phone'] = $customerData['phone1'];
        $customerData['address_details'] = $customerData['address'];
        $customerData['create_user'] = $customerData['createuser'];
        $customerData['area'] = $customerData['district'];
        return $customerData;
    }


    public function updateCustomer ($data, $id)
    {
        $result = Db::table("bgcrm.sales_source_$id")->where('customer_code="'.$data['customer_code'].'"')->update($data);
        return $result;
    }


    /**
     * 创造一个客户编码 不能循环调用!
     * @return string 客户编码
     */
    protected function createCustomerCode ()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        $i = mt_rand(10000,99999);
        return $orderSn.$i;
    }


    /**
     * 通话记录
     * @param  string $id    任务id
     * @param  string $where 搜索条件
     * @return array         通话记录数据
     */
    public function taskRecordsList($id, $where)
    {
        $page = $_REQUEST["page"];
        $limit = $_REQUEST["limit"];

        $menuname = "Call Platform";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname]; 
        $username = $_SESSION["user_info"]["username"];
        
        $count = Db::table("bgcrm.sales_cdr_$id")->where($where)->count();
        // 查询状态为1的用户数据 并且每页显示10条数据
        $taskList = Db::table("bgcrm.sales_cdr_$id")->where($where)->limit(($page-1)*$limit,$limit)->select();
        // echo $taskList;exit;
        // print_r($taskList);exit;
        $cdr_status_row = array('ANSWERED'=>'转人工已接','AUTOCALL'=>'外呼失败','NO ANSWER'=>'转人工未接','PLAYIVR'=>"未转接",'BUSY'=>'忙',"FAILED"=>"外呼失败");
        $cdr_calltype_row = array('preview'=>'预览式外呼','autocall'=>'自动外呼');
        $success_row = array('Y'=>'成功单录音','N'=>'非成功单录音');
        foreach ($taskList as &$val) {
            $status = $cdr_status_row[$val["disposition"]];
            $val["disposition"] = $status;
            $calltypes = $cdr_calltype_row[$val["calltype"]];
            $val["calltype"] = $calltypes;
            $success_enable = $success_row[$val["success_enable"]];
            $val["success_enable"] = $success_enable;
            $val["billsec"] = sprintf("%02d",intval($val["billsec"]/3600)).":".sprintf("%02d",intval(($val["billsec"]%3600)/60)).":".sprintf("%02d",intval((($val[billsec]%3600)%60)));
            //判断号码是否加密
            if($priv["encrypt_phone"] == "Y"){
                if($username != "admin"){
                    $val["src"] = substr($val["src"],0,3)."*****".substr($val["src"],-2);
                }
            }
        }
        $rowsList = count($taskList) ? $taskList : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;
        return $arrData;
    }


    /**
     * 获取收货地址
     * @param  string $customer_code 获取条件
     * @return json                  地区数据
     */
    public function getAddress ($customer_code, $id)
    {
        // $result = Db::name('vip_customer_address')->where('customer_code', $customer_code)->find();
        $result = Db::table("bgcrm.sales_source_$id")->field('province, city, district, address')->where('customer_code="'.$customer_code.'"')->find();
        $result['area'] = $result['district'];
        $result['address_details'] = $result['address'];
        // print_r($result);exit;
        return $result;
    }

}